/* $RCSFile: CRMImageItem.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageSettings/UI/WebControls/CRMImageItem.cs $
 * $log$
 * Revision 7 2010/08/09 09:44:02  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.Xml;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.UI;
using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.CRMImage.UI.WebControls
{

    
    /// <summary>
    /// CRMImageItem
    /// </summary>
    public class CRMImageItem : UserControl 
    {

        #region metadata management
        
        protected ImageMetaData _metadata   =   new ImageMetaData();
        
        public ImageMetaData Metadata
        {
            get { return _metadata; }
            set { _metadata = value; }
        }

        public string GetMetadata(string key)
        {
            return Metadata.GetMetadata(key);
        }

        /// <summary>
        /// metadata format version
        /// With version zero, shortdescription and longdescription were htmlencoded in db, which was very expensive
        /// version 1 suppressed this
        /// </summary>
        public int mVersion
        {
            get
            {
                return Metadata.Version;
            }
        }

        public void AddMetadataElement(XmlElement element)
        {
            Metadata.AppendElement(element);
        }

        public XmlElement AddMetadataElement(string elementName,string Val)
        {
            return Metadata.CreateElement(elementName,Val);
        }

        #endregion metadata management

        #region thumbnail size image and properties used in aspx, ascx

        /// <summary>
        /// The DB caption field
        /// </summary>
        public string imageCaption
		{
			get
			{
				return GetMetadata(ImStr.DBCaption);
			}
		}


		public string imageShortDescription
		{
			get
			{
                string str  =   GetMetadata(ImStr.DBShortDescription);
                if ( mVersion == 0 )
				    return Server.HtmlDecode(str);
				return str;
			}
		}

		public string imageLongDescription
		{
			get
			{
                string str  =   GetMetadata(ImStr.DBLongDescription);
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem imageLongDescription GET BEG : '{0}'.",str),CrmImageTrace.Sw.Info);
                if ( mVersion == 0 )
				    return Server.HtmlDecode(str);
				return str;
			}
		}

		public string imageCategory
		{
			get
			{
                string str  =   GetMetadata(ImStr.CatId);
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem imageCategory GET BEG CatId: '{0}'.",str),CrmImageTrace.Sw.Info);
				return str;
			}
		}

		public string imageCategoryText
		{
			get
			{
                string str  =   GetMetadata(ImStr.CatId);
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem imageCategory GET BEG CatId: '{0}'.",str),CrmImageTrace.Sw.Info);
                int catId   =   0;
                if (int.TryParse(str, out catId))
                {
                    str     =    ((CRMPage)Page).Wrapper.Util.PickListData(ImStr.adncategory, ImStr.adnimage, catId);
                    if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem imageCategory GET Crm Category: '{0}'.",str),CrmImageTrace.Sw.Info);
                }
				return str;
			}
		}

        /// <summary>
        /// String value for the int DB key for the image attached to this CRMImageItem
        /// </summary>
        public string imageDBID
		{
			get
			{
				return GetMetadata(ImStr.ImageDBID);
			}
		}

        /// <summary>
        /// String value for the int DB key for previous image if exists
        /// </summary>
        public string previousImageDBID
		{
			get
			{
				return GetMetadata("PreviousImageDBID");
			}
		}

        /// <summary>
        /// String value for the int DB key for next image if exists
        /// </summary>
        public string nextImageDBID
		{
			get
			{
				return GetMetadata("NextImageDBID");
			}
		}

		/// <summary>
		/// Thumbnail image physical path : AlbumPath + "/" + ThumbnailFilename;
		/// </summary>
        public string imageSrc
		{
			get
			{
                try
                {
                    string str = GetMetadata(ImStr.MetaAlbumPath) + "/" + GetMetadata(ImStr.ThumbnailFilename);
                    if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem imageSrc type:{0}, imageSrc: [{1}]", GetType(), str),CrmImageTrace.Sw.Info);
                    return str;
                }
                catch (Exception ex)
                {
                    if ( CrmImageTrace.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageItem imageSrc type:{0}, ex: [{1}]", GetType(), ex),CrmImageTrace.Sw.Info);
                    throw;
                }
			}
		}

        /// <summary>
        /// Width for thumbnail image
        /// </summary>
		public string thumbnailWidth
		{
			get
			{
				string str  =   GetMetadata(ImStr.MetaThumbnailWidth);
				if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem thumbnailWidth type:{0}, thumbnailWidth: [{1}]",GetType(),str),CrmImageTrace.Sw.Info);						
                return str;
			}
		}

        /// <summary>
        /// Height for thumbnail image
        /// </summary>
		public string thumbnailHeight
		{
			get
			{
				return GetMetadata(ImStr.MetaThumbnailHeight);
				}
        }
        
        #endregion thumbnail size image and properties used in aspx, ascx
        
        #region fullsize images properties used in aspx, ascx
        
		/// <summary>
		/// Full size image physical path : AlbumPath + "/" + ModifiedFilename;
		/// </summary>
        public string imageModifiedSrc
		{
			get
			{
                try
                {
                    string str = GetMetadata(ImStr.MetaAlbumPath) + "/" + GetMetadata(ImStr.ModifiedFilename);
                    if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem imageModifiedSrc type:{0}, imageSrc: [{1}]", GetType(), str),CrmImageTrace.Sw.Info);
                    return str;
                }
                catch (Exception ex)
                {
                    if ( CrmImageTrace.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageItem imageModifiedSrc type:{0}, ex: [{1}]", GetType(), ex),CrmImageTrace.Sw.Info);
                    throw;
                }
			}
		}

        /// <summary>
        /// Width for full size image
        /// </summary>
        public string modifiedWidth
		{
			get
			{
				return  GetMetadata(ImStr.MetaModifiedWidth);
			}
		}

        /// <summary>
        /// Height for full size image
        /// </summary>
		public string modifiedHeight
		{
			get
			{
				return GetMetadata(ImStr.MetaModifiedHeight);
				}
		}
        
        #endregion fullsize properties used in aspx, ascx
        
        #region path to edit/view/Add


        /// <summary>
        /// Used to crate querystring for edit or add urls
        /// Contains any necessary values to edit 
        /// Also contains any return values necessary to reposition calling page on same items
        /// </summary>
        public virtual string StdArgString
        {
            get
            {
				string str  =   string.Format("ImageDBID={0}&ItemCrmID={1}&typename={2}&id={3}&mid={4}&CatId={5}&SortKey={6}&PageNum={7}",
                    new object[]{GetMetadata(ImStr.ImageDBID),
                        GetMetadata(ImStr.ItemCrmID),
                        GetMetadata(ImStr.RequestEntityName),
                        GetMetadata(ImStr.EntityID),
                        GetMetadata(ImStr.ModuleID),
                        GetMetadata(ImStr.CatFilterId),
                        GetMetadata(ImStr.SortKey),
                        GetMetadata(ImStr.PageNum)});
                    if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem StdArgString GET:{0}", str),CrmImageTrace.Sw.Info);
                return str;
            }
        }

        /// <summary>
        /// Url to edit page
        /// </summary>
		public virtual string imageEdit
		{
			get
			{
                // we force typename and id to values get from DB, this will drive CRMPage to behave as if it was under CRM
                // even when not under CRM
				return HttpUrlBuilder.BuildUrl(Config.ModulesPath+"/CRMImage/CRMImageEdit.aspx",StdArgString);
            }
		}

		/// <summary>
		/// Command argument to delete command buttons
		/// </summary>
        public virtual string imageDelete
		{
			get
			{
				string str  =   GetMetadata(ImStr.ImageDBID);
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem imageDelete ImageDBID:{0}", str),CrmImageTrace.Sw.Info);
                return str;
            }
		}

        /// <summary>
        /// Url to View page
        /// </summary>
        public virtual string imageView
		{
			get
			{
                // we force typename and id to values get from DB, this will drive CRMPage to behave as if it was under CRM
                // even when not under CRM
				return HttpUrlBuilder.BuildUrl(Config.ModulesPath+"/CRMImage/CRMImageView.aspx",StdArgString);
			}
		}

		public virtual string PrevImageView
		{
			get
			{
				string str = string.Format("ItemCrmID={0}&ImageDBID={1}&typename={2}&id={3}&mid={4}&CatId={5}&SortKey={6}&PageNum={7}",
                    new object[]{GetMetadata("PreviousItemCrmID"),
                        GetMetadata("PreviousImageDBID"),
                        GetMetadata(ImStr.RequestEntityName),
                        GetMetadata(ImStr.EntityID),
                        GetMetadata(ImStr.ModuleID),
                        GetMetadata(ImStr.CatFilterId),
                        GetMetadata(ImStr.SortKey),
                        GetMetadata(ImStr.PageNum)});
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem PrevImageView GET:{0}", str),CrmImageTrace.Sw.Info);
				return HttpUrlBuilder.BuildUrl(Config.ModulesPath+"/CRMImage/CRMImageView.aspx",str);
			}
		}
		public virtual string NextImageView
		{
			get
			{
				string str = string.Format("ItemCrmID={0}&ImageDBID={1}&typename={2}&id={3}&mid={4}&CatId={5}&SortKey={6}&PageNum={7}",
                    new object[]{GetMetadata("NextItemCrmID"),
                        GetMetadata("NextImageDBID"),
                        GetMetadata(ImStr.RequestEntityName),
                        GetMetadata(ImStr.EntityID),
                        GetMetadata(ImStr.ModuleID),
                        GetMetadata(ImStr.CatFilterId),
                        GetMetadata(ImStr.SortKey),
                        GetMetadata(ImStr.PageNum)});
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem NextImageView GET:{0}", str),CrmImageTrace.Sw.Info);
				return HttpUrlBuilder.BuildUrl(Config.ModulesPath+"/CRMImage/CRMImageView.aspx",str);
			}
		}
        #endregion path to edit/view/Add
        
        #region various image properties
        public virtual bool ImageIsEditable
        {
            get
            {
                return ( GetMetadata(ImStr.IsEditable).ToLower() == "true" );
            }
        }

        public virtual bool ImageIsDeletable
        {
            get
            {
                return ( GetMetadata(ImStr.IsDeletable).ToLower() == "true" );
            }
        }
        #endregion various image properties

        #region properties to simulate CRMPage

        public int ModuleID
        {
            get
            {
                return int.Parse(GetMetadata(ImStr.ModuleID));
            }
        }

        public string IsUnderCRM
        {
            get
            {
                return GetMetadata(ImStr.IsUnderCRM);
            }
        }

        public string EntityName
        {
            get
            {
                return GetMetadata(ImStr.DBEntityName);
            }
        }

        public string RequestEntityName
        {
            get
            {
                return GetMetadata(ImStr.RequestEntityName);
            }
        }

        /// <summary>
        /// Guid value key for the CRM adnImage entity
        /// </summary>
        public Guid CRMEntId
        {
            get
            {
                string guidStr  =   GetMetadata(ImStr.EntityID);
                Guid CRMEId     =   Guid.Empty;
                if (!string.IsNullOrEmpty(guidStr))
                {
                    try
                    {
                        CRMEId = new Guid(guidStr);
                    }
                    catch(Exception ex)
                    { 
 				        if ( CrmImageTrace.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageItem CRMEntId GuidStr: {0}, ex: {1}",guidStr,ex),CrmImageTrace.Sw.Info);						
                   }
                }
                return CRMEId;
            }
        }
        #endregion properties to simulate CRMPage 

        #region Binding to DB Data

        public void BindFromDB(DbDataRecord di,string AlbumPath,
            int imageItemID, 
            bool IsEditable,
            bool IsDeletable,
            string RequestEntityName,
            string EntityName,
            int ModuleID,
            int ItemIndex,
            int pageNum,
            int catFilterId,
            string sortKey)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem BindFromDB BEG FieldCount: {0},",di.FieldCount),CrmImageTrace.Sw.Info);
			try
			{
                if (di[ImStr.DBMetadataXml] == DBNull.Value)
                {
				    if ( CrmImageTrace.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageItem BindFromDB corrupted Database EntityName: {0}", RequestEntityName),CrmImageTrace.Sw.Info);
                    return;
                }
                string metastr                      =   (string)di[ImStr.DBMetadataXml];
				if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem BindFromDB metadata: {0}", metastr),CrmImageTrace.Sw.Info);
                try
                {
                    Metadata.LoadXml(metastr);
                }
			    catch (Exception ex)
			    {
				    if ( CrmImageTrace.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageItem BindFromDB LoadXml ex : {0}.", ex),CrmImageTrace.Sw.Info);
                    throw;
			    }
                // metadata format version: if not defined it is zero and add it
                int metaVersion                 =   Metadata.Version;
    		    if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem BindFromDB Metadata Version: {0}.",metaVersion),CrmImageTrace.Sw.Info);

				AddMetadataElement(ImStr.MetaAlbumPath,AlbumPath);

				AddMetadataElement(ImStr.ItemID,imageItemID.ToString());

				AddMetadataElement(ImStr.ImageDBID,di[ImStr.DBImageId].ToString());

				AddMetadataElement(ImStr.ModuleID,ModuleID.ToString());

                AddMetadataElement(ImStr.DBShortDescription,(string)di[ImStr.DBShortDescription]);

                XmlElement xIsEditable				=   AddMetadataElement(ImStr.IsEditable,IsEditable.ToString());
				if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem BindFromDB IsEditable: {0}", xIsEditable.Attributes["Value"].Value),CrmImageTrace.Sw.Info);

                XmlElement xIsDeletable				=   AddMetadataElement(ImStr.IsDeletable,IsDeletable.ToString());
				if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem BindFromDB xIsDeletable: {0}", xIsEditable.Attributes["Value"].Value),CrmImageTrace.Sw.Info);

				AddMetadataElement(ImStr.RequestEntityName,RequestEntityName);

				AddMetadataElement(ImStr.EntityID,di[ImStr.DBCrmImageId].ToString()); // beware we dont have the brass {} around Guid value ???

				AddMetadataElement(ImStr.DBEntityName,EntityName);

                AddMetadataElement(ImStr.CatId,di[ImStr.DBCategory].ToString());

                AddMetadataElement(ImStr.CatFilterId,catFilterId.ToString());
                AddMetadataElement(ImStr.PageNum,pageNum.ToString());
                AddMetadataElement(ImStr.SortKey,sortKey);

                ID                                  =   string.Format("ImgItm_{0}",ItemIndex);
			    if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageItem BindFromDB CRMImgItem.ID: {0}.",ID),CrmImageTrace.Sw.Info);
			}
			catch (Exception ex)
			{
				if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageItem BindFromDB ex : {0}.", ex),CrmImageTrace.Sw.Info);
                throw;
			}
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageItem BindFromDB END.",CrmImageTrace.Sw.Info);
		}
        #endregion Binding to DB data
    }
}